<script setup lang="ts">
import * as utils from "@/utils/utils";
import btn from "@/utils/buttonInterface";

let symMapping: Map<string, string>;

// loading flag
const loading = ref<boolean>(false);
// response data
const showData = ref<showDataImpl[]>([]);
// input的输入值
const inputValue = ref<String>("");

interface showDataImpl {
  name: string;
  values: string[];
}
interface response {
  dictResStr: string[];
  fragment: string[];
  texture: string[];
  textureMod: string[];
}

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
function formatResponse(res: response) {
  // init showData
  showData.value = [];
  for (const key in res) {
    let temp: showDataImpl = {
      name: symMapping.get(key) ?? key,
      values: (res as any)[key],
    };
    showData.value.push(temp);
  }
}

const getAddrTexture = async () => {
  if (utils.Str_isEmpty(inputValue.value)) return;
  // 开启等待
  loading.value = true;
  try {
    let texture_promise = await btn.getAddrTexture(inputValue.value);
    const res: response = texture_promise["data"];
    formatResponse(res);
    await sleep(100);
    // 拿到数据关闭等待
    loading.value = false;
  } catch (e) {
    showData.value = [];
    loading.value = false;
    console.log(e);
  }
};

// 监听input的值是否和response的值对齐
watch(
  () => inputValue,
  (newFlag) => {
    if (newFlag.value === "") showData.value = [];
  },
  { deep: true }
);

// 组件挂载成功
onMounted(() => {
  symMapping = new Map();
  symMapping.set("dictResStr", "四段分词");
  symMapping.set("fragment", "解析碎片");
  symMapping.set("texture", "解析纹理");
  symMapping.set("textureMod", "纹理调整");
});

// 组件卸载时
onUnmounted(() => {
  symMapping.clear();
});
</script>

<template>
  <!-- v-on="$attrs" 没有 为什么也可以 传自定义事件？ -->
  <SkewXCard
    v-on="$attrs"
    :loading="loading"
    :show-data="showData"
    :enter-event="getAddrTexture"
    v-model:model-value="inputValue"
  />
</template>

<style scoped></style>
